package com.example.apiproject.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.apiproject.entity.GroupMembers;
import com.example.apiproject.entity.Messages;
import com.example.apiproject.service.GroupMembersService;
import com.example.apiproject.service.impl.GroupMembersServiceImpl;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class WebsocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    GroupMembersService groupMembersServiceAuto;

    private static GroupMembersService groupMembersService;

    @PostConstruct
    public void init(){
        groupMembersService = this.groupMembersServiceAuto;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        Command command = JSON.parseObject(frame.text(), Command.class);
        switch (CommandType.match(command.getCode())){
            case CONNECTION :  this.connect(ctx, command);
//            default : ctx.channel().writeAndFlush(Result.fail("不支持的code"));
        }


    }

    public static void chat(Messages messages) {
        try{
            int type = messages.getType();  // type是消息类型，0标识用户，1标识群组
            if(type == 0) {   // 私聊
                Channel channel = IMserver.USERS.get(String.valueOf(messages.getToId()));
                if(null == channel){
                    System.out.println("该 channel 不存在");
                }if(!channel.isActive()) {
                    System.out.println("该 channel 失活");
                }else {
                    channel.writeAndFlush(Result.success(JSONObject.toJSONString(messages)));
                }
            } else {   // 群聊，在前面加上字符串 group
                ChannelGroup group = IMserver.GROUP.get("group" + messages.getToId());
                if(null == group){
                    System.out.println("该 group 不存在");
                }else {
                    group.writeAndFlush(Result.success(JSONObject.toJSONString(messages)));
                }
            }

        }catch (Exception e){
            System.out.println(e);
        }

    }

    private void connect(ChannelHandlerContext ctx, Command command) {
        String id = command.getId();
        IMserver.USERS.put(id, ctx.channel());
        System.out.println(id+"连接建立成功");
        // 加入群聊
        List<String> gIds = groupMembersService.queryByUserId(id);
        for (String gId:gIds) {
            ChannelGroup group = IMserver.GROUP.get("group" + gId);
            if (null == group){
                // 添加群聊组
                IMserver.GROUP.put("group" + gId, new DefaultChannelGroup(GlobalEventExecutor.INSTANCE));
                group = IMserver.GROUP.get("group" + gId);
            }
            // 用户加入群聊
            group.add(ctx.channel());
            System.out.println("群 "+ gId +" 连接建立成功");
        }
    }
}
